<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\CostBill;
use app\common\model\DinnerRecord;
use EasyWeChat\Factory;

class Dinner extends Api
{
    protected $noNeedLogin = ['oauth_login', 'refresh_token'];
    protected $noNeedPermission = ['*'];

    public function initialize()
    {
        parent::initialize();
    }


    public function order_dinner()
    {




        if (\app\admin\model\User::where(['id' => $this->auth->id])->value('group_id') != 1) {
            $this->error('暂不支持外部人员使用');
        }
        if (!$this->request->post('type')) {
            $this->error('订餐餐次不能为空');
        }
//        if (strtotime($this->request->post('date')) + 24 * 3600 < time()) {
//            $this->error('订餐日期只能为今天以后的');
//        }
        if (DinnerRecord::where(['user_id' => $this->auth->id, 'type' => $this->request->post('type'), 'date' => $this->request->post('date')])->value('id')) {
            $this->error('您已订该日' . $this->getMealTypeText($this->request->post('type')) . ',请勿重复');
        }
        DinnerRecord::create([
            'type' => $this->request->post('type'),

            'date' => $this->request->post('date'),
            'user_id' => $this->auth->id
        ]);

        $user = \app\admin\model\User::find($this->auth->id);
        $text = '好友' . $user['nickname'] . '已为您完成订餐，请及时核实';
        $config = [
            'app_id' => 'wx56c979d82ef6e40d',
            'secret' => '71b08c91f4f06acfa635249ae9ffb9f9',

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__ . '/wechat.log',
            ],
        ];
        $type_text = $this->request->post('type') == 1 ? '今日中餐' : '今日晚餐';
        //avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
        //city: ""
        //country: ""
        //gender: 0
        //language: ""
        //nickName: "微信用户"
        //province: ""

        $app = Factory::miniProgram($config);
        $user_list = \app\admin\model\User::whereIn('id',$this->request->post('uid'))->select();
        foreach ($user_list as $key => $value) {

            if (!DinnerRecord::where(['user_id' => $value['id'], 'type' => $this->request->post('type'), 'date' => $this->request->post('date')])->value('id')) {
                DinnerRecord::create([
                    'type' => $this->request->post('type'),

                    'date' => $this->request->post('date'),
                    'user_id' => $value['id']
                ]);
                $data = [
                    'template_id' => 'PoqanOeFN4jqEbpPIV-HoGmDmUz5MrpkB3JF1R5_dko', // 所需下发的订阅模板id
                    'touser' => $value['openid'],     // 接收者（用户）的 openid
                    'page' => 'pages/addmbook/addmbook',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'thing1' => [
                            'value' => $value['nickname'],
                        ],
                        'thing2' => [
                            'value' => $type_text,
                        ],
                        'time3' => [
                            'value' => date('Y-m-d'),
                        ],
                        'thing4' => [
                            'value' => $text,
                        ],
                    ],
                ];

                $r = $app->subscribe_message->send($data);
            }




        }


        $this->success('成功');
    }

    private function getMealTypeText($type)
    {
        return ['', '早餐', '午餐', '晚餐'][$type];
    }

    public function delete_dinner()
    {
        if (\app\admin\model\User::where(['id' => $this->auth->id])->value('group_id') != 1) {
            $this->error('暂不支持外部人员使用');
        }
        if (!$this->request->post('id')) {
            $this->error('id不能为空');
        }

        if (DinnerRecord::where(['id' => $this->request->post('id')])->value('user_id') != $this->auth->id) {
            $this->error('只能删除自己的订餐');
        }
        // 软删除
        DinnerRecord::destroy($this->request->post('id'));

        $this->success('成功');
    }
}